package com.sinsz.common.exception;


import com.sinsz.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 异常捕获器
 * @author chenjianbo
 * @date 2018-3-30
 */
@RestControllerAdvice
public class ApiExceptionAdvice {

    private final HttpServletRequest request;

    private static final Logger log = LoggerFactory.getLogger(ApiExceptionAdvice.class);

    @Autowired
    public ApiExceptionAdvice(HttpServletRequest request) {
        this.request = request;
    }

    @ExceptionHandler({ApiException.class, RuntimeException.class, Exception.class})
    public Result handlerArithmeticException(Exception ex) {
        String remoteHost = request.getRemoteHost();
        String requestUri = request.getRequestURI();
        String method = request.getMethod();
        log.error("请求地址:{}, 路径:{}, 请求方式:{}, 异常信息:{}",remoteHost, requestUri,method, ex);
        if (ex instanceof ApiException) {
            ApiException exception = (ApiException) ex;
            return Result.fail(exception.getError(), ex.getCause());
        } else {
            return Result.systemError();
        }
    }

}
